package com.easy.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.easy.common.util.Result;
import com.easy.common.util.SYS;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;

import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.List;
@Component//添加过滤器
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    private static final List<String> ALLOWED_PATHS =
            Arrays.asList("/api/user/dologin", "/api/user/register", "/api/user/login/captcha", "/api/user/login/userDoLogin", "/api/user/login/adminDoLogin",
                    "/user/dologin", "/user/register", "/user/login/captcha", "/user/login/userDoLogin", "/user/login/adminDoLogin","/user/login/logininfo","/user/login/send-reset-code"
                    ,"/user/login/verify-reset-code","/user/login/reset-password-by-email","/user/upload/file");
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri= request.getURI();
        String path = uri.getPath();
        System.out.println("path---------------"+path);
        
        System.out.println("当前请求路径：" + path);
        
        // 检查是否在白名单中
        for (String allowedPath : ALLOWED_PATHS) {
            System.out.println("检查白名单路径：" + allowedPath);
            if (path.equals(allowedPath) || path.startsWith(allowedPath + "/")) {
                System.out.println("路径完全匹配或前缀匹配成功，放行：" + path);
                return chain.filter(exchange);
            }
        }
        
        // 特别为验证码API添加匹配规则
        if (path.contains("/login/captcha")) {
            System.out.println("验证码API路径包含匹配成功，放行：" + path);
            return chain.filter(exchange);
        }
        
        // 为登录API添加特别匹配规则
        if (path.contains("/login/userDoLogin") || path.contains("/login/adminDoLogin")) {
            System.out.println("登录API路径包含匹配成功，放行：" + path);
            return chain.filter(exchange);
        }
        //验证有没有登录
        //获取token
        String token = request.getHeaders().getFirst(SYS.TOKEN_AUTHORIZATION);
        //判断token是否为空，是否有效，如果认证模块，在此通过Dubbo服务获取token是否有效
        if(token==null){
            return unauthorizedResponse(exchange, Result.fail(401, "未认证"));
        }
        //验证token通过就放行
        return chain.filter(exchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, Result result) {

        String json= JSON.toJSONString(result);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json");
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(json.getBytes())));
    }

    @Override
    //这个方法确定过滤器的执行顺序，数字越小越先执行
    public int getOrder() {
        return 0;
    }
}
